<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import { FormRules,FormInstance, ElMessage,ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus';
import {ArrowDown} from '@element-plus/icons-vue';
import {home} from "@/api/home.ts";

import request from "@/utils/request.ts";


onMounted(() => {
  getVideoList(selectedStatus.value)
  getTask()
})
// 定义状态映射
const statusMap = {
  1: '待处理',
  2: '处理中',
  3: '处理完成',
  4: '字幕视频合成完毕',
  5: '音频合成完毕',
  6: '处理失败',
};

// 当前选中的状态
const selectedStatus = ref(1);

// 处理状态选择事件
const handleStatusChange = (status: number) => {
  selectedStatus.value = status;
  console.log(selectedStatus.value)
  getVideoList(status)
  videoList.length = 0; // 清空视频列表
};
const videoList = reactive<{
  clay_material: string;
  collection_end_time: string;
  collection_start_time: string;
  craftsman_name: string;
  create_id: string;
  create_name: string;
  create_time: string;
  description?: any;
  enabled: string;
  filename: string;
  id: number;
  original_path: string;
  remark?: any;
  status: number;
  update_id: string;
  update_name: string;
  update_time: string;
  user_id: number;
  uuid: string;
  valid: string;
  version?: any;
  video_uuid: string;
}[]>([])

const getVideoList = (value: any) => {
  home.getVideoList(value).then((res) => {
    loading.value = false
    console.log(res.data)
    videoList.push(...res.data)
  })
};

// 根据状态返回标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case 1:
      return 'info'; // 待处理
    case 2:
      return 'warning'; // 处理中
    case 3:
      return 'success'; // 处理完成
    case 4:
      return 'success'; // 字幕视频合成完毕
    case 5:
      return 'success'; // 音频合成完毕
    case 6:
      return 'danger'; // 处理失败
    default:
      return 'info';
  }
};

interface User {
  clay_material: string;
  collection_end_time: string;
  collection_start_time: string;
  craftsman_name: string;
  create_id: string;
  create_name: string;
  create_time: string;
  description?: any;
  enabled: string;
  filename: string;
  id: number;
  original_path: string;
  remark?: any;
  status: number;
  update_id: string;
  update_name: string;
  update_time: string;
  user_id: number;
  uuid: string;
  valid: string;
  version?: any;
  video_uuid: string;
}


const handleEdit = async (index: number, row: User) => {
  console.log(index, row)
  const formData = new FormData();
  formData.append('analysis_uuid', row.uuid);

  try {
    const response = await request.post(import.meta.env.VITE_SERVE+'/api/v1/videos/process6', formData, {
      headers: {
        'Content-Type': 'application/json',
      },
    });
    ElMessage.success('分析成功');
    console.log(response.data);
  } catch (error) {
    ElMessage.error('分析失败');
    console.error(error);
  }
}

const loading = ref(true)

const isToke = ref(false)
const getTask = () => {
  home.getTask().then((res: { data: { has_running_tasks: boolean } }) => {
    console.log(res)
    isToke.value = res.data.has_running_tasks

    // isToke.value = false
  })
}

const addAudioDialog = ref(false)
const addAudio = reactive({
  analysis_uuid: '',
  audio_file: [] as any[],
})
const upload = ref()
const formLabelWidth = '140px'
const handleAddAudio = (index: number, row: User) => {
  console.log(index, row)
 addAudio.analysis_uuid = row.uuid
  addAudioDialog.value = true
}

const handleChange = (file: File, fileList: File[]) => {
  console.log('File changed:', file, fileList);
  addAudio.audio_file = fileList;
};

const handleSuccess = (response: any, file: File, fileList: File[]) => {
  console.log('Upload success:', response, file, fileList);
  // ElMessage.success('音频上传成功');
};

const beforeUpload = (file: File) => {
  const isAudio = file.type === 'audio/mpeg' || file.type === 'audio/wav';
  if (!isAudio) {
    ElMessage.error('只能上传音频文件!');
  }
  return isAudio;
};

const handleConfirm = async () => {
  // 处理确认逻辑
  if (addAudio.audio_file) {
    const formData = new FormData();
    addAudio.audio_file.forEach((file) => {
      console.log(file?.raw);
      formData.append('audio_file', file?.raw);
    });
    formData.append('analysis_uuid', addAudio.analysis_uuid);
    console.log(formData);
    home.getUploadAudio(formData).then((res) => {
      console.log(res);
      ElMessage.success('音频上传成功');
      addAudioDialog.value = false;
      // 清空音频列表
      addAudio.audio_file = [];
    }).catch((error) => {
      ElMessage.error('音频上传失败');
    });
  } else {
    ElMessage.error('请先上传音频文件');
  }
};


const subtitleDialog = ref(false)
const subtitle = reactive({
  analysis_uuid: '',
  first_text: '',
  second_text: '',
  segment: 0,
})
const handleaddABarrage = (index: number, row: User) => {
  console.log(index, row)
  subtitle.analysis_uuid = row.uuid
  subtitleDialog.value = true
}
const formRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  analysis_uuid: [{required: true, message: '请输入唯一id',  trigger: 'change',}],
  segment: [{required: true, message: '请输入间隔时间', trigger: 'change',}],
  first_text: [{required: true, message: '请输入第一段字幕', trigger: 'change',}],
  second_text: [{required: true, message: '第二段字幕', trigger: 'change',}],
})
const addSubtitles = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid:any
      , fields:any) => {
    if (valid) {
      home.getSubtitle(subtitle.analysis_uuid, subtitle.segment,subtitle.first_text, subtitle.second_text).then((res) => {
        console.log(res)
        ElMessage.success('添加弹幕成功！');
        subtitleDialog.value = false
      }).catch(() => {
        ElMessage.error('添加弹幕失败！');
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

</script>

<template>
  <div>
    <el-row class="rounded-box">
      <el-col :span="20">
        <el-dropdown @command="handleStatusChange">
          <span class="el-dropdown-link">
            {{ statusMap[selectedStatus] }} <el-icon class="el-icon--right"><ArrowDown/></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :command="1">待处理</el-dropdown-item>
              <el-dropdown-item :command="2">处理中</el-dropdown-item>
              <el-dropdown-item :command="3">处理完成</el-dropdown-item>
              <el-dropdown-item :command="4">字幕视频合成完毕</el-dropdown-item>
              <el-dropdown-item :command="5">音频合成完毕</el-dropdown-item>
              <el-dropdown-item :command="6">处理失败</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
      <el-col :span="2">
        <el-tag size="large" :type="isToke ? 'danger' : 'primary'" >{{
            isToke ? '有任务在处理' : '暂无处理任务'
          }}</el-tag>
      </el-col>
    </el-row>
    <el-row class="rounded-box">
      <el-col :span="24">
        <el-table :data="videoList" style="width: 100%; margin-top: 20px;" v-loading="loading">
          <el-table-column prop="uuid" label="视频唯一标识符"></el-table-column>
          <el-table-column prop="filename" label="原始文件名"></el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ statusMap[scope.row.status] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="original_path" label="原始视频存储路径"></el-table-column>
          <el-table-column prop="collection_start_time" label="采集开始时间"></el-table-column>
          <el-table-column prop="collection_end_time" label="采集结束时间"></el-table-column>
          <el-table-column prop="create_time" label="创建"></el-table-column>
          <el-table-column prop="clay_material" label="泥料材质"></el-table-column>
          <el-table-column prop="craftsman_name" label="工艺师姓名"></el-table-column>
          <el-table-column prop="update_name" label="更新人姓名"></el-table-column>
          <el-table-column prop="update_time" label="更新时间"></el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="scope">
              <div class="button-container">
                <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)"
                >分析视频
                </el-button>
                <el-button type="primary" size="small" @click="handleAddAudio(scope.$index, scope.row)"
                >添加音频
                </el-button>
                <el-button type="primary" size="small" @click="handleaddABarrage(scope.$index, scope.row)"
                >添加字幕
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog v-model="addAudioDialog" title="添加音频">
      <el-form :model="addAudio">
        <el-form-item label="上传音频文件" :label-width="formLabelWidth">
          <el-upload
              ref="upload"
              class="upload-demo"
              action="http://192.168.0.47:5001/api/v1/videos/audio"
              :on-change="handleChange"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
              :limit="1"
              :file-list="addAudio.audio_file"
              :auto-upload="true"
              accept=".mp3,.wav"
          >
            <template #trigger>
              <el-button type="primary">上传音频</el-button>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="唯一id" :label-width="formLabelWidth">
          <el-input v-model="addAudio.analysis_uuid" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addAudioDialog = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="subtitleDialog" title="添加字幕">
      <el-form :model="subtitle" :label-width="formLabelWidth" ref="formRef" :rules="rules">
        <el-form-item label="唯一id" prop="analysis_uuid">
          <el-input v-model="subtitle.analysis_uuid" placeholder="请填写唯一id"/>
        </el-form-item>
        <el-form-item label="间隔时间" prop="segment">
          <el-input v-model="subtitle.segment" placeholder="请填写间隔时间"/>
        </el-form-item>
        <el-form-item label="第一段字幕" prop="first_text">
          <el-input v-model="subtitle.first_text" placeholder="请填写第一段字幕"/>
        </el-form-item>
        <el-form-item label="第二段字幕" prop="second_text">
          <el-input v-model="subtitle.second_text" placeholder="请填写第二段字幕"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="subtitleDialog = false">取消</el-button>
          <el-button type="primary" @click="addSubtitles(formRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.rounded-box {
  background-color: white;
  margin: 10px;
  padding: 20px;
  border-radius: 10px;
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}


.button-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  height: 100%; /* 确保容器高度占满单元格 */
  gap: 10px; /* 按钮之间的间距 */
}
</style>
